package com.oz.ems.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;

import javax.servlet.ServletContext;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Each;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import com.oz.ems.Utils;
import com.oz.ems.bean.Demo;

@IocBean
@At("/demo")
@Ok("raw:json")
public class DemoAction {
	@Inject // 注入同名的一个ioc对象
	protected Dao dao;

	private static final Log log = Logs.getLog(DemoAction.class);

	@At("/list")
	public Object demoList(ServletContext sc,String name, int p, int pageSize, String region, String start, String end, String orderBy) {
//		log.debug(".....................当前路径是............."+sc.getRealPath("/"));
		Criteria cri = Cnd.cri();
		if (Strings.isNotBlank(name))
			cri.where().and("name", "like", "%" + name + "%");
		if (Strings.isNotBlank(region))
			cri.where().and("region", "like", "" + region + "");
		if (Strings.isNotBlank(start)) {
			cri.where().and("date1", ">=",start.replaceAll("^(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)$", "$1-$2-$3"));
		}
		if (Strings.isNotBlank(end)) {
			cri.where().and("date1", "<=", end.replaceAll("^(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)$", "$1-$2-$3"));
		}
		if (Strings.isNotBlank(orderBy)) {
			Lang.each(orderBy.split(","), new Each<String>() {
				public void invoke(int i, String ele, int length) {
					cri.getOrderBy().orderBy(ele.split(" ")[0], ele.split(" ")[1]);
				}
			});
		}
		Pager pager = dao.createPager(p, pageSize);
		QueryResult qr = new QueryResult();
		qr.setList(dao.query(Demo.class, cri, pager));
		pager.setRecordCount(dao.count(Demo.class, cri));
		qr.setPager(pager);
		
		log.debug(".....得到界面...." + Json.toJson(qr.getPager(), JsonFormat.compact()));

		return Json.toJson(new HashMap<String, Object>() {
			private static final long serialVersionUID = 1L;
			{
				put("code", 20000);
				put("list", qr.getList());
				put("pageNum",
						qr.getPager().getPageNumber() > qr.getPager().getPageCount() ? qr.getPager().getPageCount()
								: qr.getPager().getPageNumber());
				put("total", qr.getPager().getRecordCount());
			}
		}, JsonFormat.tidy());// 默认分页是第1页,每页20条
	}

	@At("/createorupdate")
	public Object createOrUpdate(@Param("..") Demo demo) {
		log.debug("....得到上传.....demoentity....." + Json.toJson(demo, JsonFormat.full()));
		if (Strings.isBlank(demo.getId())) {
			demo.setId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
			dao.insert(demo);
		} else
			dao.update(demo);
		return "{\"code\":20000,\"rId\":\"" + demo.getId() + "\"}";
	}

	@At("/delete")
	public Object deleteDemoEntity(String id) {
		log.debug("....得到上传.....demoentity....." + Json.toJson(id));
		int deletedCount = dao.delete(Demo.class, id);
		return "{\"code\":20000,\"deletedCount\":\"" + deletedCount + "\"}";
	}


	@At("/upload")
	@AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
//	@AdaptBy(type = UploadAdaptor.class, args = { "ioc:myUpload" })
	public Object upEntity(@Param("upfs") TempFile tf,ServletContext context) {
		log.info("----Utils.getFilsPath---path------------> " + Utils.getFilesPath());
		// 这个是保存的临时文件
		String fileName = "",timeString = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(Calendar.getInstance().getTime());
		String shortPath = timeString.substring(0, 10);

		if (tf != null) {
			File longPath = new File(Utils.getFilesPath() + File.separator + shortPath);
			if (!longPath.exists())
				longPath.mkdirs();
			fileName = longPath.getAbsolutePath() + File.separator + timeString + tf.getSubmittedFileName();
			try {
				tf.write(fileName);
				tf.delete();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			log.info("上传文件保存路径是:  " + shortPath + "/" + timeString + tf.getSubmittedFileName());
		}
		return "{\"code\":\"20000\",\"url\":\"" + shortPath + "/" + timeString + tf.getSubmittedFileName() + "\"}";
	}
}
